import type { App, DirectiveBinding } from 'vue'
import { useUserStore } from '@/stores/modules/user'
import { hasPermission } from '@/utils/permission'

/**
 * 权限指令
 * 用法:
 * 1. v-permission="'admin'" - 检查用户是否具有指定角色
 * 2. v-permission="['admin', 'coach']" - 检查用户是否具有任一角色
 */

export const permission = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding)
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding)
  }
}

function checkPermission(el: HTMLElement, binding: DirectiveBinding) {
  const userStore = useUserStore()
  const { value } = binding

  if (!userStore.userInfo) {
    el.style.display = 'none'
    return
  }

  let hasPermission = false

  if (typeof value === 'string') {
    // 单个角色检查
    hasPermission = userStore.userInfo.role === value
  } else if (Array.isArray(value)) {
    // 多个角色检查
    hasPermission = value.includes(userStore.userInfo.role)
  } else {
    // 默认显示
    hasPermission = true
  }

  el.style.display = hasPermission ? '' : 'none'
}

// 注册指令
export default {
  install(app: App) {
    app.directive('permission', permission)
  }
}
